import { login, logout, getInfo } from '@/api/admin'
import { getCookie, setCookie, removeCookie } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getCookie('adminToken'),
    adminId: parseInt(getCookie('adminId')),
    authorityId: parseInt(getCookie('authorityId')),
    nickName: getCookie('adminNickName'),
    avatarUrl: getCookie('adminAvatarUrl')
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, nickName) => {
    state.nickName = nickName
  },
  SET_AVATAR: (state, avatarUrl) => {
    state.avatarUrl = avatarUrl
  },
  SET_AUTHORITY_ID: (state, authorityId) => {
    state.authorityId = authorityId
  },
  SET_ADMIN_ID: (state, adminId) => {
    state.adminId = adminId
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        const { data } = response
        commit('SET_TOKEN', data.token)
        setCookie('adminToken', data.token)
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response

        if (!data) {
          return reject('验证失败，请重新登录')
        }

        const { nickName, avatarUrl, id, authorityId } = data

        commit('SET_NAME', nickName)
        setCookie('adminNickName', nickName)

        commit('SET_AVATAR', avatarUrl)
        setCookie('adminAvatarUrl', avatarUrl)

        commit('SET_ADMIN_ID', id)
        setCookie('adminId', id)

        commit('SET_AUTHORITY_ID', authorityId)
        setCookie('authorityId', authorityId)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout().then(() => {
        removeCookie('adminToken') // must remove  token  first
        removeCookie('authorityId')
        removeCookie('adminNickName')
        removeCookie('adminAvatarUrl')
        removeCookie('adminId')
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeCookie('adminToken') // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

